package cmd

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"github.com/twwch/gin-sdk/constant"
	"twwch/k8s-admin/config"
	"twwch/k8s-admin/server"
	"twwch/k8s-admin/websocket"

	"github.com/spf13/cobra"
)

var (
	Version string
	Commit  string
	Date    string

	cfgFile string
)

func init() {
	rootCmd.Flags().BoolP("runGrpc", "g", false, "run grpc server")
	rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./config/test.toml", "config file (default is ./config/test.toml)")
}

var (
	conf    *config.Config
	rootCmd = &cobra.Command{
		Use:     "k8s-admin",
		Short:   fmt.Sprintf("TEMPLATE\nCommit: %s\nDate: %s", Commit, Date),
		Version: Version,
		PreRun:  preRun,
		Run: func(cmd *cobra.Command, args []string) {
			ctx := context.Background()
			go func() {
				httpServer := server.New(constant.HTTPProtocal, conf.Port).(*server.HTTP)
				log.Error(ctx, httpServer.Server.Run(ctx))
			}()
			go func() {
				websocket.Run()
			}()
			select {}
		},
	}
)

// Execute command
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Fatalln(context.Background(), err)
	}
}
